package com.abe.bathsystem.contract;

import com.abe.bathsystem.api.AppMainService;
import com.abe.bathsystem.base.ManagerLocalData;
import com.abe.bathsystem.entity.ReqBaseEntity;
import com.abe.bathsystem.entity.ReqBaseNoDataEntity;
import com.abe.bathsystem.entity.ReqConstant;
import com.abe.bathsystem.entity.http.HttpAdEntity;
import com.abe.bathsystem.entity.http.HttpBathPosStateEntity;
import com.abe.bathsystem.entity.http.HttpNoticeEntity;
import com.abe.bathsystem.entity.http.HttpRoomEntity;
import com.abe.bathsystem.entity.http.HttpSensorEntity;
import com.abe.bathsystem.entity.http.HttpUserDetailEntity;
import com.abe.bathsystem.entity.http.HttpUserEntity;
import com.abe.bathsystem.entity.http.HttpVersionEntity;
import com.abe.bathsystem.utils.ConstantBath;
import com.abe.bathsystem.utils.NormalUtils;
import com.abe.libcore.utils.Utils;
import com.abe.libcore.utils.normal.CommonUtils;
import com.abe.libcore.utils.normal.FileSizeUtil;
import com.abe.libcore.utils.normal.FileUtils;
import com.abe.mvpcore.OnResultListener;
import com.google.gson.Gson;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class CommonModel implements CommonContract.Model {

    @Override
    public void uploadLog(String fullName, final OnResultListener<ReqBaseEntity<Integer>> listener) {
        listener.onStart();
        CommonUtils.w("fullName:" + fullName);
        if (FileUtils.fileIsExists(fullName)) {
            if (FileSizeUtil.getFileOrFilesSize(fullName, FileSizeUtil.SIZE_TYPE_MB) >= 20) {
                listener.onFailure("选中日志超过20M");
                listener.onEnd();
            } else {
                File file = new File(fullName);
                RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), file);
                MultipartBody.Part body = MultipartBody.Part.createFormData("aFile", file.getName(), requestFile);
                Call<ReqBaseEntity<Integer>> call = AppMainService.getCommonService().uploadFile(body);
                call.enqueue(new Callback<ReqBaseEntity<Integer>>() {
                    @Override
                    public void onResponse(Call<ReqBaseEntity<Integer>> call, Response<ReqBaseEntity<Integer>> response) {
                        listener.onSuccess(response.body());
                        listener.onEnd();
                    }

                    @Override
                    public void onFailure(Call<ReqBaseEntity<Integer>> call, Throwable t) {
                        listener.onFailure("日志上传失败");
                        listener.onEnd();
                    }
                });
            }
        } else {
            listener.onFailure("选中日期无日志");
            listener.onEnd();
        }
    }

    @Override
    public void saveLogData(String resId, final OnResultListener<ReqBaseNoDataEntity> listener) {
        listener.onStart();
        HttpRoomEntity entity = ManagerLocalData.getRoomData();
        if (entity == null) {
            listener.onFailure("服务器信息缺失");
            listener.onEnd();
            return;
        }
        Call<ReqBaseNoDataEntity> call = AppMainService.getCommonService().saveLogData(entity.getRoomId(), resId);
        call.enqueue(new Callback<ReqBaseNoDataEntity>() {
            @Override
            public void onResponse(Call<ReqBaseNoDataEntity> call, Response<ReqBaseNoDataEntity> response) {
                listener.onSuccess(response.body());
                listener.onEnd();
            }

            @Override
            public void onFailure(Call<ReqBaseNoDataEntity> call, Throwable t) {
                listener.onFailure(t.getMessage());
                listener.onEnd();
            }
        });
    }

    @Override
    public void checkVersion(final OnResultListener<ReqBaseEntity<HttpVersionEntity>> listener) {
        listener.onStart();
        if (CommonUtils.getMetaBooleanData(Utils.getContext(), "NetDebug")) {
            HttpVersionEntity versionEntity = new HttpVersionEntity();
            versionEntity.setPkgName(NormalUtils.getPkgName());
            versionEntity.setVersionName(NormalUtils.getVersionName());
            versionEntity.setVersionCode(NormalUtils.getVersionCode());
            listener.onSuccess(new ReqBaseEntity<>(0, null, versionEntity));
        } else {
            Call<ReqBaseEntity<HttpVersionEntity>> call = AppMainService.getCommonService().checkVersion(NormalUtils.getPkgName());
            call.enqueue(new Callback<ReqBaseEntity<HttpVersionEntity>>() {
                @Override
                public void onResponse(Call<ReqBaseEntity<HttpVersionEntity>> call, Response<ReqBaseEntity<HttpVersionEntity>> response) {
                    listener.onSuccess(response.body());
                    listener.onEnd();
                }

                @Override
                public void onFailure(Call<ReqBaseEntity<HttpVersionEntity>> call, Throwable t) {
                    CommonUtils.w("CommonModel-checkVersion:" + t.getMessage());
                    listener.onFailure(t.getMessage());
                    listener.onEnd();
                }
            });
        }
    }

    @Override
    public void getRoomData(final OnResultListener<ReqBaseEntity<HttpRoomEntity>> listener) {
        listener.onStart();
        if (CommonUtils.getMetaBooleanData(Utils.getContext(), "NetDebug")) {
            HttpRoomEntity roomEntity = new HttpRoomEntity();
            roomEntity.setRoomId("1005");
            roomEntity.setDownloadImage(ConstantBath.AD_IMG_TEMP[0]);
            roomEntity.setServerTime(String.valueOf(new Date().getTime()));
            roomEntity.setLoginUrl("http://www.liantu.com/images/2013/weixin.png");
            roomEntity.setFee_chong_dian(0.5);
            roomEntity.setFee_chui_feng(1.5);
            roomEntity.setFee_xi_yi(1);
            roomEntity.setFee_xi_yu_da(0.5);
            roomEntity.setFee_xi_yu_xiao(1);
            roomEntity.setPrepay_chong_dian(20);
            roomEntity.setPrepay_xi_yi(20);
            roomEntity.setPrepay_chui_feng(20);
            roomEntity.setPrepay_xi_yu(20);
            listener.onSuccess(new ReqBaseEntity<>(0, null, roomEntity));
            listener.onEnd();
        } else {
            String mac = NormalUtils.getMac(Utils.getContext(), false);
            CommonUtils.w("mac:" + mac);
            Call<ReqBaseEntity<HttpRoomEntity>> call = AppMainService.getCommonService().getRoomInfo(mac);
            call.enqueue(new Callback<ReqBaseEntity<HttpRoomEntity>>() {
                @Override
                public void onResponse(Call<ReqBaseEntity<HttpRoomEntity>> call, Response<ReqBaseEntity<HttpRoomEntity>> response) {
                    listener.onSuccess(response.body());
                    listener.onEnd();
                }

                @Override
                public void onFailure(Call<ReqBaseEntity<HttpRoomEntity>> call, Throwable t) {
                    CommonUtils.w("CommonModel-getRoomInfo:" + t.getMessage());
                    listener.onFailure(t.getMessage());
                    listener.onEnd();
                }
            });
        }
    }

    @Override
    public void getAdData(final OnResultListener<ReqBaseEntity<List<HttpAdEntity>>> listener) {
        listener.onStart();
        HttpRoomEntity entity = ManagerLocalData.getRoomData();
        if (entity == null) {
            listener.onFailure("服务器信息缺失");
            listener.onEnd();
            return;
        }
        if (CommonUtils.getMetaBooleanData(Utils.getContext(), "NetDebug")) {
            List<HttpAdEntity> adEntities = new ArrayList<>();
            String[] x = {
                    "http://jzvd.nathen.cn/c6e3dc12a1154626b3476d9bf3bd7266/6b56c5f0dc31428083757a45764763b0-5287d2089db37e62345123a1be272f8b.mp4",
                    "http://jzvd.nathen.cn/c6e3dc12a1154626b3476d9bf3bd7266/6b56c5f0dc31428083757a45764763b0-5287d2089db37e62345123a1be272f8b.mp4",
                    "http://img.pconline.com.cn/images/upload/upc/tx/wallpaper/1301/28/c0/17788267_1359354035165.jpg",
                    "http://img.mp.itc.cn/upload/20170324/663c85eae74f4320a3e382f03af76d52_th.jpg",
                    "http://jzvd.nathen.cn/c6e3dc12a1154626b3476d9bf3bd7266/6b56c5f0dc31428083757a45764763b0-5287d2089db37e62345123a1be272f8b.mp4"};
            int[] y = {1, 1, 0, 0, 1};
            for (int i = 0; i < x.length; i++) {
                HttpAdEntity adItemEntity = new HttpAdEntity();
                adItemEntity.setAdType(y[i]);
                adItemEntity.setUrl(x[i]);
                adItemEntity.setWeight(1);
                adEntities.add(adItemEntity);
            }
            ReqBaseEntity<List<HttpAdEntity>> reqBaseEntity = new ReqBaseEntity<>();
            reqBaseEntity.setCode(0);
            reqBaseEntity.setData(adEntities);
            listener.onSuccess(reqBaseEntity);
            listener.onEnd();
        } else {
            Call<ReqBaseEntity<List<HttpAdEntity>>> call = AppMainService.getCommonService().getAdData(entity.getRoomId());
            call.enqueue(new Callback<ReqBaseEntity<List<HttpAdEntity>>>() {
                @Override
                public void onResponse(Call<ReqBaseEntity<List<HttpAdEntity>>> call, Response<ReqBaseEntity<List<HttpAdEntity>>> response) {
                    listener.onSuccess(response.body());
                    listener.onEnd();
                }

                @Override
                public void onFailure(Call<ReqBaseEntity<List<HttpAdEntity>>> call, Throwable t) {
                    CommonUtils.w("CommonModel-getAdData:" + t.getMessage());
                    listener.onFailure(t.getMessage());
                    listener.onEnd();
                }
            });
        }
    }

    @Override
    public void getRoomStatus(final OnResultListener<ReqBaseEntity<List<HttpBathPosStateEntity>>> listener) {
        listener.onStart();
        HttpRoomEntity entity = ManagerLocalData.getRoomData();
        if (entity == null) {
            listener.onFailure("服务器信息缺失");
            listener.onEnd();
            return;
        }
        if (CommonUtils.getMetaBooleanData(Utils.getContext(), "NetDebug")) {
            List<HttpBathPosStateEntity> entities = new ArrayList<>();
            entities.add(new HttpBathPosStateEntity(0, ReqConstant.BATH_POS_STATE_BATHING, "15550012633", new Date().getTime()));
            entities.add(new HttpBathPosStateEntity(1, ReqConstant.BATH_POS_STATE_NO, "", new Date().getTime()));
            entities.add(new HttpBathPosStateEntity(2, ReqConstant.BATH_POS_STATE_FAULT, "", new Date().getTime()));
            entities.add(new HttpBathPosStateEntity(3, ReqConstant.BATH_POS_STATE_RESERVE, "18754126016", new Date().getTime()));
            entities.add(new HttpBathPosStateEntity(4, ReqConstant.BATH_POS_STATE_NO, "", new Date().getTime()));
            entities.add(new HttpBathPosStateEntity(5, ReqConstant.BATH_POS_STATE_NO, "", new Date().getTime()));
            entities.add(new HttpBathPosStateEntity(6, ReqConstant.BATH_POS_STATE_NO, "", new Date().getTime()));
            entities.add(new HttpBathPosStateEntity(7, ReqConstant.BATH_POS_STATE_NO, "", new Date().getTime()));
            listener.onSuccess(new ReqBaseEntity<>(0, null, entities));
            listener.onEnd();
        } else {
            Call<ReqBaseEntity<List<HttpBathPosStateEntity>>> call = AppMainService.getCommonService().getRoomStatus(entity.getRoomId());
            call.enqueue(new Callback<ReqBaseEntity<List<HttpBathPosStateEntity>>>() {
                @Override
                public void onResponse(Call<ReqBaseEntity<List<HttpBathPosStateEntity>>> call, Response<ReqBaseEntity<List<HttpBathPosStateEntity>>> response) {
                    listener.onSuccess(response.body());
                    listener.onEnd();
                }

                @Override
                public void onFailure(Call<ReqBaseEntity<List<HttpBathPosStateEntity>>> call, Throwable t) {
                    CommonUtils.w("CommonModel-getRoomStatus:" + t.getMessage());
                    listener.onFailure(t.getMessage());
                    listener.onEnd();
                }
            });
        }
    }

    private HttpUserEntity getTempUser() {
        HttpUserEntity userEntity = new HttpUserEntity();
        HttpUserDetailEntity entity = new HttpUserDetailEntity();
        entity.setPhone("15550012633");
        entity.setName("张三");
        userEntity.setUser(entity);
        return userEntity;
    }

    @Override
    public void login(String phone, String password, final OnResultListener<ReqBaseEntity<HttpUserEntity>> listener) {
        listener.onStart();
        HttpRoomEntity entity = ManagerLocalData.getRoomData();
        if (entity == null) {
            listener.onFailure("服务器信息缺失");
            listener.onEnd();
            return;
        }
        if (CommonUtils.getMetaBooleanData(Utils.getContext(), "NetDebug")) {
            ReqBaseEntity<HttpUserEntity> reqBaseEntity = new ReqBaseEntity<>();
            reqBaseEntity.setCode(0);
            reqBaseEntity.setData(getTempUser());
            listener.onSuccess(reqBaseEntity);
            listener.onEnd();
        } else {
            Call<ReqBaseEntity<HttpUserEntity>> call = AppMainService.getCommonService().login(entity.getRoomId(), ReqConstant.NET_OS, phone, password);
            call.enqueue(new Callback<ReqBaseEntity<HttpUserEntity>>() {
                @Override
                public void onResponse(Call<ReqBaseEntity<HttpUserEntity>> call, Response<ReqBaseEntity<HttpUserEntity>> response) {
                    listener.onSuccess(response.body());
                    listener.onEnd();
                }

                @Override
                public void onFailure(Call<ReqBaseEntity<HttpUserEntity>> call, Throwable t) {
                    CommonUtils.w("CommonModel-login:" + t.getMessage());
                    listener.onFailure(t.getMessage());
                    listener.onEnd();
                }
            });
        }
    }

    @Override
    public void updateBathPosState(int position, int status, int sensor01, int sensor02, final OnResultListener<ReqBaseNoDataEntity> listener) {
        listener.onStart();
        HttpRoomEntity entity = ManagerLocalData.getRoomData();
        if (entity == null) {
            listener.onFailure("服务器信息缺失");
            listener.onEnd();
            return;
        }
        if (CommonUtils.getMetaBooleanData(Utils.getContext(), "NetDebug")) {
            listener.onSuccess(new ReqBaseNoDataEntity(0, "OK"));
            listener.onEnd();
        } else {
            String x = "[\"0\":" + sensor01 + ",\"1\":" + sensor02 + "]";
            String json = "{\"position\":" + position + ",\"status\":" + status + ",\"sensors\":" + x + "}";
            CommonUtils.w(json);
            Call<ReqBaseNoDataEntity> call = AppMainService.getCommonService().report(entity.getRoomId(), json, "", "");
            call.enqueue(new Callback<ReqBaseNoDataEntity>() {
                @Override
                public void onResponse(Call<ReqBaseNoDataEntity> call, Response<ReqBaseNoDataEntity> response) {
                    listener.onSuccess(response.body());
                    listener.onEnd();
                }

                @Override
                public void onFailure(Call<ReqBaseNoDataEntity> call, Throwable t) {
                    CommonUtils.w("CommonModel-report:" + t.getMessage());
                    listener.onFailure(t.getMessage());
                    listener.onEnd();
                }
            });
        }
    }


    @Override
    public void uploadClientId(String id, final OnResultListener<ReqBaseNoDataEntity> listener) {
        listener.onStart();
        HttpRoomEntity entity = ManagerLocalData.getRoomData();
        if (entity == null) {
            listener.onFailure("服务器信息缺失");
            listener.onEnd();
            return;
        }
        if (CommonUtils.getMetaBooleanData(Utils.getContext(), "NetDebug")) {
            listener.onSuccess(new ReqBaseNoDataEntity(0, "OK"));
            listener.onEnd();
        } else {
            Call<ReqBaseNoDataEntity> call = AppMainService.getCommonService().upload(entity.getRoomId(), id, "1");
            call.enqueue(new Callback<ReqBaseNoDataEntity>() {
                @Override
                public void onResponse(Call<ReqBaseNoDataEntity> call, Response<ReqBaseNoDataEntity> response) {
                    listener.onSuccess(response.body());
                    listener.onEnd();
                }

                @Override
                public void onFailure(Call<ReqBaseNoDataEntity> call, Throwable t) {
                    CommonUtils.w("CommonModel-upload:" + t.getMessage());
                    listener.onFailure(t.getMessage());
                    listener.onEnd();
                }
            });
        }
    }

    @Override
    public void orderStart(HttpUserEntity userEntity, HttpBathPosStateEntity posStateEntity, final OnResultListener<ReqBaseNoDataEntity> listener) {
        HttpRoomEntity entity = ManagerLocalData.getRoomData();
        if (entity == null) {
            listener.onFailure("服务器信息缺失");
            listener.onEnd();
            return;
        }
        if (CommonUtils.getMetaBooleanData(Utils.getContext(), "NetDebug")) {
            listener.onSuccess(new ReqBaseNoDataEntity(0, "OK"));
            listener.onEnd();
        } else {
            Call<ReqBaseNoDataEntity> call = AppMainService.getCommonService().start(entity.getRoomId(), 0, userEntity.getUser().getPhone(),
                    String.valueOf(posStateEntity.getPos()), System.currentTimeMillis());
            call.enqueue(new Callback<ReqBaseNoDataEntity>() {
                @Override
                public void onResponse(Call<ReqBaseNoDataEntity> call, Response<ReqBaseNoDataEntity> response) {
                    listener.onSuccess(response.body());
                    listener.onEnd();
                }

                @Override
                public void onFailure(Call<ReqBaseNoDataEntity> call, Throwable t) {
                    CommonUtils.w("CommonModel-start:" + t.getMessage());
                    listener.onFailure(t.getMessage());
                    listener.onEnd();
                }
            });
        }
    }

    @Override
    public void orderEnd(HttpUserEntity userEntity, HttpBathPosStateEntity posStateEntity, float xi_yu_da, float xi_yu_xiao, float fee_total, float fee_xi_yu_da, float fee_xi_yu_xiao, float fee_chui_feng, float fee_chong_dian, final OnResultListener<ReqBaseNoDataEntity> listener) {
        HttpRoomEntity entity = ManagerLocalData.getRoomData();
        if (entity == null) {
            listener.onFailure("服务器信息缺失");
            listener.onEnd();
            return;
        }
        if (CommonUtils.getMetaBooleanData(Utils.getContext(), "NetDebug")) {
            listener.onSuccess(new ReqBaseNoDataEntity(0, "OK"));
            listener.onEnd();
        } else {
            Map<String, Object> params = new HashMap<>();
            params.put("roomId", entity.getRoomId());
            params.put("type", 0);
            params.put("phone", userEntity.getUser().getPhone());
            params.put("position", String.valueOf(posStateEntity.getPos()));
            params.put("time", System.currentTimeMillis());
            params.put("xi_yu_da", xi_yu_da);
            params.put("xi_yu_xiao", xi_yu_xiao);
            params.put("fee_total", fee_total);
            params.put("fee_xi_yu_da", fee_xi_yu_da);
            params.put("fee_xi_yu_xiao", fee_xi_yu_xiao);
            params.put("fee_chui_feng", fee_chui_feng);
            params.put("fee_chong_dian", fee_chong_dian);
            params.put("qr", false);
            Call<ReqBaseNoDataEntity> call = AppMainService.getCommonService().end(params);
            call.enqueue(new Callback<ReqBaseNoDataEntity>() {
                @Override
                public void onResponse(Call<ReqBaseNoDataEntity> call, Response<ReqBaseNoDataEntity> response) {
                    listener.onSuccess(response.body());
                    listener.onEnd();
                }

                @Override
                public void onFailure(Call<ReqBaseNoDataEntity> call, Throwable t) {
                    CommonUtils.w("CommonModel-end:" + t.getMessage());
                    listener.onFailure(t.getMessage());
                    listener.onEnd();
                }
            });
        }
    }

    @Override
    public void getNotice(final OnResultListener<ReqBaseEntity<List<HttpNoticeEntity>>> listener) {
        HttpRoomEntity entity = ManagerLocalData.getRoomData();
        if (entity == null) {
            listener.onFailure("服务器信息缺失");
            listener.onEnd();
            return;
        }
        if (CommonUtils.getMetaBooleanData(Utils.getContext(), "NetDebug")) {
            List<HttpNoticeEntity> entities = new ArrayList<>();
            String[] x = {"1111111111111", "22222222222222", "3333333333333333", "44444444444444444"};
            for (int i = 0; i < x.length; i++) {
                entities.add(new HttpNoticeEntity(i, new Date().getTime(), x[i], x[i], null));
            }
            listener.onSuccess(new ReqBaseEntity<>(0, "OK", entities));
            listener.onEnd();
        } else {
            Call<ReqBaseEntity<List<HttpNoticeEntity>>> call = AppMainService.getCommonService().getNotice(entity.getRoomId());
            call.enqueue(new Callback<ReqBaseEntity<List<HttpNoticeEntity>>>() {
                @Override
                public void onResponse(Call<ReqBaseEntity<List<HttpNoticeEntity>>> call, Response<ReqBaseEntity<List<HttpNoticeEntity>>> response) {
                    listener.onSuccess(response.body());
                    listener.onEnd();
                }

                @Override
                public void onFailure(Call<ReqBaseEntity<List<HttpNoticeEntity>>> call, Throwable t) {
                    CommonUtils.w("CommonModel-getNotice:" + t.getMessage());
                    listener.onFailure(t.getMessage());
                    listener.onEnd();
                }
            });
        }
    }

    @Override
    public void uploadSensorData(List<HttpSensorEntity> sensorEntities, final OnResultListener<ReqBaseNoDataEntity> listener) {
        HttpRoomEntity entity = ManagerLocalData.getRoomData();
        if (entity == null) {
            listener.onFailure("服务器信息缺失");
            listener.onEnd();
            return;
        }
        if (CommonUtils.getMetaBooleanData(Utils.getContext(), "NetDebug")) {
            listener.onSuccess(new ReqBaseNoDataEntity(0, "OK"));
            listener.onEnd();
        } else {
            Call<ReqBaseNoDataEntity> call = AppMainService.getCommonService().uploadSensorInfo(entity.getRoomId(), new Gson().toJson(sensorEntities));
            call.enqueue(new Callback<ReqBaseNoDataEntity>() {
                @Override
                public void onResponse(Call<ReqBaseNoDataEntity> call, Response<ReqBaseNoDataEntity> response) {
                    listener.onSuccess(response.body());
                    listener.onEnd();
                }

                @Override
                public void onFailure(Call<ReqBaseNoDataEntity> call, Throwable t) {
                    CommonUtils.w("CommonModel-uploadSensorInfo:" + t.getMessage());
                    listener.onFailure(t.getMessage());
                    listener.onEnd();
                }
            });
        }
    }
}